﻿/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
using Yama.MVC.Core.Models;
using Yama.MVC.Dao;
using Yama.MVC.Dao.Repositories;
using Yama.MVC.NHibernate.Connections;
using Yama.Util.CodeContracts;

namespace Yama.MVC.NHibernate.Repositories
{
    ///<summary>
    /// A generic repository using NHibernate persistence
    ///</summary>
    public abstract class GenericDao<TId, T> : IDao<TId, T> where T : Entity<TId>
    {
        protected ISessionProvider provider;

        protected ISession CurrentSession
        {
            get { return provider.CurrentSession; }
        }

        protected GenericDao(ISessionProvider provider)
        {
            this.provider = provider;
        }

        #region Helper methods

        static ICriteria GetAssociationCriteria(ICriteria query, string associationPath, out string property)
        {
            int lastDot = associationPath.LastIndexOf('.');
            string assocPath = associationPath.Substring(0, lastDot);
            property = associationPath.Substring(lastDot + 1);

            ICriteria criteriaByPath = query.GetCriteriaByPath(assocPath);
            if(criteriaByPath == null)
            {
                criteriaByPath = query;
                foreach (string pathFragment in assocPath.Split('.'))
                {
                    criteriaByPath = criteriaByPath.CreateCriteria(pathFragment);
                }
            }

            return criteriaByPath;
        }

        protected IList<T> AutoList(ICriteria query, int firstResult, int pageSize, string sortColumn, SortDirection sortDirection, out long totalCount)
        {
            ICriteria count = (ICriteria)query.Clone();

            if (!string.IsNullOrEmpty(sortColumn))
                ApplyOrders(query, new Dictionary<string, SortDirection> { { sortColumn, sortDirection } });

            return AutoList(query, count, firstResult, pageSize, out totalCount);
        }

        protected IList<T> AutoList(ICriteria query, int firstResult, int pageSize, out long totalCount)
        {
            ICriteria count = (ICriteria)query.Clone();

            return AutoList(query, count, firstResult, pageSize, out totalCount);
        }

        private IList<T> AutoList(ICriteria query, ICriteria count, int firstResult, int pageSize, out long totalCount)
        {
            Check.Require(typeof(T).Equals(query.GetRootEntityTypeIfAvailable()), "Root entity type must match repository's generic class type parameter");

            var totalCountReturn = ApplyCountProjection(count).FutureValue<long>();
            var suppliers = SetPage(query, firstResult, pageSize).Future<T>();

            totalCount = totalCountReturn.Value;
            return suppliers.ToList();
        }
   

        #endregion

        #region Criteria

        protected ICriteria TypeCriteria
        {
            get { return CurrentSession.CreateCriteria(typeof(T)); }
        }

        protected ICriteria ApplyPropertiesCriteria(ICriteria criteria, IDictionary<string, object> propertyValuePairs)
        {
            ICriteria modified = criteria;

            foreach (var propertyValuePair in propertyValuePairs)
            {

                if (propertyValuePair.Key.Contains("."))
                {
                    string property;
                    ICriteria association = GetAssociationCriteria(modified, propertyValuePair.Key, out property);
                    association.Add(Restrictions.Eq(property, propertyValuePair.Value));
                }
                else
                    modified = modified.Add(Restrictions.Eq(propertyValuePair.Key, propertyValuePair.Value));
            }

            return modified;
        }

        protected ICriteria ApplyOrders(ICriteria criteria, IDictionary<string, SortDirection> propertyOrderPairs)
        {
            ICriteria modified = criteria;

            foreach (var propertyOrderPair in propertyOrderPairs)
            {
                bool sortAscending = propertyOrderPair.Value == SortDirection.Ascending;

                if(propertyOrderPair.Key.Contains("."))
                {
                    string property;
                    ICriteria association = GetAssociationCriteria(modified, propertyOrderPair.Key, out property);
                    association.AddOrder(new Order(property, sortAscending));
                }
                else
                    modified = modified.AddOrder(new Order(propertyOrderPair.Key, sortAscending));
            }

            return modified;
        }

        protected ICriteria ApplyCountProjection(ICriteria criteria)
        {
            criteria.ClearOrders();
            return criteria.SetProjection(Projections.RowCountInt64());
        }

        protected ICriteria SetPage(ICriteria criteria, int firstResult, int pageSize)
        {
            return criteria.SetMaxResults(pageSize).SetFirstResult(firstResult);
        }

#if NET35
        protected ICriteria CreateCountCriteria(IDictionary<string, object> propertyValuePairs)
#else
        protected ICriteria CreateCountCriteria(IDictionary<string, object> propertyValuePairs = null)
#endif
        {
            ICriteria criteria = CreateCriteria(propertyValuePairs, null);
            criteria = ApplyCountProjection(criteria);

            return criteria;
        }

#if NET35
        protected ICriteria CreateCriteria(IDictionary<string, object> propertyValuePairs, IDictionary<string, SortDirection> propertyOrderPairs)
#else
        protected ICriteria CreateCriteria(IDictionary<string, object> propertyValuePairs = null, IDictionary<string, SortDirection> propertyOrderPairs = null)
#endif
        {
            ICriteria criteria = TypeCriteria;

            if (propertyValuePairs != null)
                criteria = ApplyPropertiesCriteria(criteria, propertyValuePairs);

            if (propertyOrderPairs != null)
                criteria = ApplyOrders(criteria, propertyOrderPairs);

            return criteria;
        }

        #endregion

        #region Implementation of IDao<T>

        public virtual IList<T> FindAll()
        {
#warning "Consider using PagedFind. See more on http://nhprof.com/Learn/Alerts/UnboundedResultSet"
            return FindAll(null, null);
        }

        public IList<T> FindAll(IDictionary<string, object> propertyValuePairs)
        {
#warning "Consider using PagedFind. See more on http://nhprof.com/Learn/Alerts/UnboundedResultSet"
            return FindAll(propertyValuePairs, null);
        }

        public IList<T> FindAll(IDictionary<string, SortDirection> propertyOrderPairs)
        {
#warning "Consider using PagedFind. See more on http://nhprof.com/Learn/Alerts/UnboundedResultSet"
            return FindAll(null, propertyOrderPairs);
        }

        public IList<T> FindAll(IDictionary<string, object> propertyValuePairs, IDictionary<string, SortDirection> propertyOrderPairs)
        {
#warning "Consider using PagedFind. See more on http://nhprof.com/Learn/Alerts/UnboundedResultSet"
            return CreateCriteria(propertyValuePairs, propertyOrderPairs).List<T>();
        }

        public T FindOne()
        {
            return FindOne(null, null);
        }

        public T FindOne(IDictionary<string, object> propertyValuePairs)
        {
            return FindOne(propertyValuePairs, null);
        }

        public T FindOne(IDictionary<string, SortDirection> propertyOrderPairs)
        {
            return FindOne(null, propertyOrderPairs);
        }

        public T FindOne(IDictionary<string, object> propertyValuePairs, IDictionary<string, SortDirection> propertyOrderPairs)
        {
            IMultiCriteria query = CurrentSession.CreateMultiCriteria();
            ICriteria countCriteria = CreateCountCriteria(propertyValuePairs);
            ICriteria queryCriteria = CreateCriteria(propertyValuePairs, propertyOrderPairs).SetMaxResults(1);

            query.Add("count", countCriteria);
            query.Add("query", queryCriteria);

            long count = (long) query.GetResult("count");

            if(count > 1)
            {
                throw new DaoException(string.Format("Query should return only 1 result but returned {0}", count));
            }

            return (T) query.GetResult("query");
        }

        public T FindFirst()
        {
            return FindFirst(null, null);
        }

        public T FindFirst(IDictionary<string, object> propertyValuePairs)
        {
            return FindFirst(propertyValuePairs, null);
        }

        public T FindFirst(IDictionary<string, SortDirection> propertyOrderPairs)
        {
            return FindFirst(null, propertyOrderPairs);
        }

        public T FindFirst(IDictionary<string, object> propertyValuePairs, IDictionary<string, SortDirection> propertyOrderPairs)
        {
            return CreateCriteria(propertyValuePairs, propertyOrderPairs).SetMaxResults(1).UniqueResult<T>();
        }

        public IList<T> PagedFind(int firstResult, int pageSize, out long totalCount)
        {
            return PagedFind(firstResult, pageSize, out totalCount, null, null);
        }

        public IList<T> PagedFind(int firstResult, int pageSize, out long totalCount, IDictionary<string, object> propertyValuePairs)
        {
            return PagedFind(firstResult, pageSize, out totalCount, propertyValuePairs, null);
        }

        public IList<T> PagedFind(int firstResult, int pageSize, out long totalCount, IDictionary<string, SortDirection> propertyOrderPairs)
        {
            return PagedFind(firstResult, pageSize, out totalCount, null, propertyOrderPairs);
        }

        public IList<T> PagedFind(int firstResult, int pageSize, out long totalCount, IDictionary<string, object> propertyValuePairs, IDictionary<string, SortDirection> propertyOrderPairs)
        {
            IMultiCriteria multiCriteria = CurrentSession.CreateMultiCriteria();

            ICriteria selectCriteria = CreateCriteria(propertyValuePairs, propertyOrderPairs);
            ICriteria countCriteria = CreateCountCriteria(propertyValuePairs);

            IList results = multiCriteria
                .Add(SetPage(selectCriteria, firstResult, pageSize))
                .Add(countCriteria)
                .List();

            totalCount = ((IList)results[1]).Count > 0 ? (long)((IList)results[1])[0] : 0;
            return ((IList)results[0]).Cast<T>().ToList();
        }

        public virtual T FindById(TId identity)
        {
            return CurrentSession.Get<T>(identity);
        }

        public virtual T Save(T instance)
        {
            CurrentSession.Save(instance);

            return instance;
        }

        public virtual void DeleteAll()
        {
            foreach (var instance in FindAll())
            {
                CurrentSession.Delete(instance);
            }
        }

        public virtual void SaveAll(IList<T> instances)
        {
            foreach (var instance in instances)
            {
                CurrentSession.SaveOrUpdate(instance);
            }
        }

        public virtual void Update(T instance)
        {
            CurrentSession.SaveOrUpdate(instance);
        }

        public virtual T Load(TId identity)
        {
            return CurrentSession.Load<T>(identity);
        }

        public long Count()
        {
            return Count(null);
        }

        public long Count(IDictionary<string, object> propertyValuePairs)
        {
            return CreateCountCriteria(propertyValuePairs).UniqueResult<long>();
        }

        #endregion

        public int BatchSize
        {
            set { CurrentSession.SetBatchSize(value); }
        }

        public void ClearAndFlushSession()
        {
            CurrentSession.Flush();
            CurrentSession.Clear();
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            CurrentSession.Dispose();
        }

        #endregion
    }
}